from socket import *
from time import ctime
import os
import random
import check
import cv2
import time
import matplotlib.pyplot as plt
from datetime import datetime

HOST = ''
PORT = 2333
BUFSIZ = 1024
c=0
ADDR = (HOST, PORT)
DATAx=[]
DATAy=[]
lfile='asd'
now=5000
tcpSerSock = socket(AF_INET, SOCK_STREAM)   #创建套接字
tcpSerSock.bind(ADDR)   #绑定IP和端口
tcpSerSock.listen(5)    #监听端口，最多5人排队

while True:
    print('waiting for connection...')
    tcpCliSock, addr = tcpSerSock.accept()    #建立连接
    print('...connected from:', addr)
    while True:
        data = tcpCliSock.recv(1024)
        #data=(str(data, encoding = "utf-8")).split('/')[-1]
        data = (str(data, encoding="utf-8"))
        while(data!="file"):
            data = tcpCliSock.recv(1024)
            data = (str(data, encoding="utf-8"))
        data = tcpCliSock.recv(1024)
        data = (str(data, encoding="utf-8")).split('/')[-1]
        if(len(data)==len('aa0.txt')):
            data=data[0:2]+'00'+data[2:]
        if (len(data) == len('aa00.txt')):
            data = data[0:2] + '0' + data[2:]
        print(data)
        DATAx.append(datetime.fromtimestamp(time.time()) .strftime('%H:%M:%S'))
        if len(DATAx)<20:
            plt.plot(DATAx[:-1], DATAy)
        else:
            plt.plot(DATAx[-21:-1], DATAy[-20:])
        plt.gcf().autofmt_xdate()
        plt.savefig('R.png')
        c=c+1
        plt.close('all')
        tcpCliSock.send(str("OK").encode("utf-8"))
        ff=data="E:/INTER/image/"+data
        f = open(data, 'w')
        f.close()
        f=open(data,'wb')
        data = tcpCliSock.recv(1024*10000*1024)
            #if not data:
             #   break
        f.write(data)
            #content = '[%s] %s' % (bytes(ctime(), "utf-8"), data)
            #print(data)
            #print(type(content))
            #tcpCliSock.send(content.encode("utf-8"))
        f.close()
        Q=0
        if lfile=='asd' or check.chheck(lfile,ff)==str(1):
            lfile = ff
        else:
            Q=1
            os.remove(ff)
            #print(ff)
        f = open('a.txt', 'w')
        f.write(str(now))
        f.close()
        tcpCliSock.send(str("OK").encode("utf-8"))
        tcpCliSock.send(str(Q).encode("utf-8"))
        data = tcpCliSock.recv(1024)
        now=data = (str(data, encoding="utf-8"))
        print(data)
        DATAy.append(int(data))


    #tcpCliSock.close()

tcpSerSock.close()